const http = require('http');

console.log('正在启动后端服务器...');

const server = http.createServer((req, res) => {
  // 设置CORS头 - 支持多个前端端口
  const allowedOrigins = [
    'http://localhost:8102',
    'http://localhost:8104',
    'http://localhost:3000',
    'http://127.0.0.1:8102',
    'http://127.0.0.1:8104'
  ];
  
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  } else {
    res.setHeader('Access-Control-Allow-Origin', '*'); // 开发环境允许所有来源
  }
  
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  res.setHeader('Access-Control-Allow-Credentials', 'true');

  if (req.method === 'OPTIONS') {
    res.writeHead(200);
    res.end();
    return;
  }

  // 路由处理
  const url = req.url;
  const method = req.method;

  console.log(`${method} ${url}`);

  // 健康检查
  if (url === '/api/health' && method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
      success: true,
      message: 'API运行正常',
      data: {
        timestamp: new Date().toISOString(),
        server: 'alternative-backend'
      }
    }));
    return;
  }

  // 登录 - 支持两个端点
  if ((url === '/api/doctors/login' || url === '/api/auth/login') && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      console.log('🔐 登录请求详情:', { url, method, body });
      try {
        const { username, password } = JSON.parse(body);
        console.log('📝 解析的凭据:', { username, password });
        if (username === 'admin' && password === 'Admin123') {
          console.log('✅ 登录验证成功');
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({
            success: true,
            message: '登录成功',
            data: {
              token: 'mock_token_' + Date.now(),
              doctor: {
                doctor_id: 1,
                username: 'admin',
                real_name: '系统管理员',
                role: 3,
                department: '信息科',
                title: '系统管理员'
              }
            }
          }));
        } else {
          console.log('❌ 登录验证失败 - 用户名或密码错误');
          res.writeHead(401, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({
            success: false,
            message: '用户名或密码错误'
          }));
        }
      } catch (error) {
        console.log('❌ JSON解析错误:', error.message);
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: false,
          message: '请求格式错误'
        }));
      }
    });
    return;
  }

  // 获取用户信息
  if (url === '/api/doctors/info' && method === 'POST') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({
      success: true,
      message: '获取用户信息成功',
      data: {
        doctor_id: 1,
        username: 'admin',
        real_name: '系统管理员',
        role: 3,
        department: '信息科',
        title: '系统管理员'
      }
    }));
    return;
  }

  // 评分结果查询
  if (url === '/api/scoring/result' && method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const { task_id } = JSON.parse(body);
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: true,
          message: '获取任务结果成功',
          data: {
            task_id: task_id,
            patient: {
              patient_id: 1,
              patient_code: 'TEST001',
              gender: 1,
              gender_name: '男',
              birthday: '1990-01-01'
            },
            doctor: {
              doctor_id: 1,
              real_name: '系统管理员',
              department: '信息科',
              title: '系统管理员'
            },
            task_info: {
              status: 3,
              status_name: '已完成',
              submit_time: new Date().toISOString(),
              complete_time: new Date().toISOString(),
              image_url: '/uploads/test.jpg',
              clinical_text: '测试临床文本'
            },
            ai_result: {
              score: 5,
              severity: 2,
              severity_name: '轻度',
              confidence: 85,
              model_version: '1.0.0',
              analysis_details: 'AI分析详情'
            }
          }
        }));
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
          success: false,
          message: '请求格式错误'
        }));
      }
    });
    return;
  }

  // 404处理
  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    success: false,
    message: '请求的资源不存在',
    url: url
  }));
});

const PORT = 4000;

server.on('error', (error) => {
  if (error.code === 'EADDRINUSE') {
    console.error(`❌ 端口 ${PORT} 被占用！`);
    console.error('请尝试以下解决方案：');
    console.error('1. 关闭占用端口的程序');
    console.error('2. 使用其他端口');
    console.error('3. 重启计算机');
  } else {
    console.error('❌ 服务器启动失败:', error);
  }
});

server.listen(PORT, () => {
  console.log(`🚀 后端服务器启动成功！`);
  console.log(`📍 服务地址: http://localhost:${PORT}`);
  console.log(`✅ /api/health - 健康检查`);
  console.log(`✅ /api/doctors/login - 登录接口`);
  console.log(`✅ /api/scoring/result - 评分结果查询`);
  console.log(`🛡️ 已启用CORS支持`);
});

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n正在关闭服务器...');
  server.close(() => {
    console.log('服务器已关闭');
    process.exit(0);
  });
});
